package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.text.SimpleDateFormat;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.DatePicker.DatePicker;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.DueDateBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import demo.cn.addapp.pickers.listeners.OnItemPickListener;
import demo.cn.addapp.pickers.listeners.OnSingleWheelListener;
import demo.cn.addapp.pickers.picker.SinglePicker;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 09 月 22.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.activity
 * 工程名 welbeing_pregnant
 */
public class CalculateDueActivity extends Activity {
    private static final String TAG ="CalculateDueActivity" ;
    @Bind(R.id.activity_calculate_iv_return)
    ImageView activityCalculateIvReturn;
    @Bind(R.id.activity_calculate_bt_determine)
    Button activityCalculateBtDetermine;
    @Bind(R.id.activity_calculate_tv_years_and_day)
    TextView activityCalculateTvYearsAndDay;
    @Bind(R.id.activity_calculate_rl_last_menstrual_period)
    RelativeLayout activityCalculateRlLastMenstrualPeriod;
    @Bind(R.id.activity_calculate_tv_day)
    TextView activityCalculateTvDay;
    @Bind(R.id.activity_calculate_rl_menstrual_cycle)
    RelativeLayout activityCalculateRlMenstrualCycle;
    @Bind(R.id.activity_calculate_rl_know_Due)
    RelativeLayout activityCalculateRlKnowDue;


    private Calendar calendar = Calendar.getInstance();
    private  final int mYear = calendar.get(Calendar.YEAR); // 获取当前年份
    private  final int mMonth = calendar.get(Calendar.MONTH) + 1;// 获取当前月份
    private  final int mday = calendar.get(Calendar.DAY_OF_MONTH); // 获取当日


    private String lastMenstrualPeriod;  //末次月经日期
    private String menstrualCycle; //月经周期天数
    private  int CalculateYear; //计算预期期的年份
    private  int CalculateMonth; //计算预期期的月份
    private  int CalculateDay; //计算预期期的日期
    private SimpleDateFormat simpleDateFormat;
    private double largestDueDate;
    private double iiiii = 24409589093.0;

    private String CalculateDue;  //计算的预产期

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculate);
        ButterKnife.bind(this);

        Utils.setStatusBar(this,false,false);
        Utils.setStatusTextColor(true,this);

        try {
            simpleDateFormat = new SimpleDateFormat("y-M-d");
            Date  date = simpleDateFormat .parse(mYear+"-"+mMonth+"-"+mday);
            String format1 = simpleDateFormat.format(date);
            largestDueDate =  (System.currentTimeMillis() + 24409589093.0);
            String format = simpleDateFormat.format(largestDueDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.activity_calculate_iv_return, R.id.activity_calculate_bt_determine, R.id.activity_calculate_tv_years_and_day, R.id.activity_calculate_rl_menstrual_cycle, R.id.activity_calculate_rl_know_Due})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_calculate_iv_return:
                Intent intent = new Intent(CalculateDueActivity.this, SetDueDateActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.activity_calculate_bt_determine: //确定
                String yearandday = activityCalculateTvYearsAndDay.getText().toString().trim();
                if(!TextUtils.isEmpty(yearandday)){
                    String day = activityCalculateTvDay.getText().toString().trim();
                    if(!TextUtils.isEmpty(day)){
                        //
                        calculateDueBtDetermine();
                    }else{
                        Toast.makeText(CalculateDueActivity.this,"请选择月经周期天数",Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(CalculateDueActivity.this,"请选择末次月经",Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.activity_calculate_tv_years_and_day: //末次月经日期
                selectLastMenstrualPeriod();
                break;
            case R.id.activity_calculate_rl_menstrual_cycle:   //末次月经日期
                selectMenstrualCycle();
                break;
            case R.id.activity_calculate_rl_know_Due:  //我知道预产期
                break;
        }
    }

    private void calculateDueBtDetermine() {
        if(lastMenstrualPeriod != null && menstrualCycle != null){
            /**----------------计算预产期------------------*/
            String[] split = lastMenstrualPeriod.split("-");
            String year = split[0];
            String month = split[1];
            String day = split[2];

            int calcuYear = Integer.parseInt(year);
            int calcuMonth = Integer.parseInt(month);
            int calcuDay = Integer.parseInt(day);
            int minMonth = calcuMonth + 9;

            int menstrualCycleday = Integer.parseInt(menstrualCycle);  //月经周期天数

            int minDay = calcuDay + 7 + menstrualCycleday;  //日期计算累加

            if(minMonth >12){  /**--------------月份大于12个月----------------*/
                CalculateYear =  calcuYear + 1;
                CalculateMonth  =  minMonth - 12;
               /* calendar.set(CalculateYear,CalculateMonth-1,1);
                int dayst =calendar.getActualMaximum(calendar.DAY_OF_MONTH);*/
                if(minDay > 30){   /**--------------日期大于当月最大天数----------------*/
                    CalculateDay = minDay - 30;
                    JudgeDueDate(CalculateYear,CalculateMonth,CalculateDay);
                }else{
                    CalculateDay = minDay;
                    JudgeDueDate(CalculateYear, CalculateMonth, CalculateDay);
                }
            }else{
                CalculateYear = calcuYear;
                CalculateMonth = minMonth;
                if(minDay > 30){  /**--------------日期大于当月最大天数----------------*/
                    CalculateDay = minDay - 30;
                    JudgeDueDate(CalculateYear, CalculateMonth, CalculateDay);
                }else{
                    CalculateDay = minDay;
                    JudgeDueDate(CalculateYear, CalculateMonth, CalculateDay);
                }
            }
        }else{
            Toast.makeText(CalculateDueActivity.this, "请选择末次月经日期和月经周期天数", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * @desc 如果计算出来的日期要大于末次月经的时间月份+182这个时间段就按照末次月经的时间月份+182的来(******************)
     * @desc 用来判断预产期的最大时间
     * @param calculateYear_01
     * @param calculateMonth_01
     * @param calculateDay_01*/
    private void JudgeDueDate(int calculateYear_01, int calculateMonth_01, int calculateDay_01) {
        try {
            Date date = simpleDateFormat.parse(calculateYear_01 + "-" + calculateMonth_01 + "-" + calculateDay_01);
            double dateTime = date.getTime();
            String format222 = simpleDateFormat.format(dateTime);
            if (dateTime >= largestDueDate) { /*--------------计算出来的日期要大于末次月经的时间月份+182-----------------------*/
                String format = simpleDateFormat.format(largestDueDate);
                CalculateDue = format;
                //将计算好的产检日期提交到后台
               // calculateDueAndPageJump(CalculateDue);
                submitCalcate(CalculateDue);
            } else {
                CalculateDue = CalculateYear + "-" + CalculateMonth + "-" + CalculateDay;
                //将计算好的产检日期提交到后台
               // calculateDueAndPageJump(CalculateDue);
                submitCalcate(CalculateDue);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * @desc 提交计算的预产期
     * @param calculateDue*/
    private void submitCalcate(String calculateDue) {
        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CHANGE_DUE_DATE)
                .addParams("cus_id", user_id)
                .addParams("care_date", calculateDue)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final DueDateBean dueDateBean =  gson.fromJson(praiseParseNetworkResponse,DueDateBean.class);
                        if(dueDateBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("user_set_due_date",dueDateBean.data); //预产期
                                    edit.commit();
                                    Intent intent = new Intent(CalculateDueActivity.this, SetDueDateActivity.class);
                                    startActivity(intent);
                                    finish();

                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),dueDateBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     * @desc 选择末次月经日期
     * */
    private void selectLastMenstrualPeriod() {
        DatePicker picker = new DatePicker(this);
        picker.setRange(2000, 2030);
        picker.setSelectedItem(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                int yearint = Integer.parseInt(year);
                int monthint = Integer.parseInt(month);
                int dayint = Integer.parseInt(day);
                if(yearint<=mYear && monthint<=mMonth && dayint<=mday ){
                    if(dayint>=10){
                        if(monthint>=mMonth-1 && dayint>= mday-10){
                            activityCalculateTvYearsAndDay.setText(year + "-" + month + "-" + day);
                            lastMenstrualPeriod = year + "-" + month + "-" + day;
                            SharedPreferences sp1 = getSharedPreferences("release_cache_data", 0);
                            SharedPreferences.Editor edit1 = sp1.edit();
                            edit1.putString("select_pregnant_mother_menstrual_period",year + "-" + month + "-" + day);
                            edit1.commit();
                        }else{
                            Toast.makeText(CalculateDueActivity.this,"你的选择超出末次月经日期有效时间范围(今天之前40~今天)",Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        if(monthint>=mMonth-2 ){ //(30+dayint-10)
                            activityCalculateTvYearsAndDay.setText(year + "-" + month + "-" + day);
                            lastMenstrualPeriod = year + "-" + month + "-" + day;
                            SharedPreferences sp1 = getSharedPreferences("release_cache_data", 0);
                            SharedPreferences.Editor edit1 = sp1.edit();
                            edit1.putString("select_pregnant_mother_menstrual_period",year + "-" + month + "-" + day);
                            edit1.commit();
                        }else{
                            Toast.makeText(CalculateDueActivity.this,"你的选择超出末次月经日期有效时间范围(今天之前40~今天)",Toast.LENGTH_SHORT).show();
                        }
                    }
                }else{
                    Toast.makeText(CalculateDueActivity.this, "你的选择超出末次月经日期有效时间范围(今天之前40~今天)", Toast.LENGTH_SHORT).show();
                }
            }
        });
        picker.show();

    }
    /**
     * @desc 选择月经周期天数
     * */
    private void selectMenstrualCycle() {
        ArrayList<String> list = new ArrayList<>();
        for(int i = 22;i<41; i++){
            list.add(i+" 天");
        }
        //        String[] ss = (String[]) list.toArray();
        SinglePicker<String> picker = new SinglePicker<>(this, list);
        picker.setCanLoop(false);//不禁用循环
        picker.setLineVisible(true);
        picker.setShadowVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(10);
        picker.setWheelModeEnable(true);
        //启用权重 setWeightWidth 才起作用
        picker.setLabel("");
        picker.setWeightEnable(true);
        picker.setWeightWidth(1);
        picker.setSelectedTextColor(0xFF279BAA);//前四位值是透明度
        picker.setUnSelectedTextColor(0xFF999999);
        picker.setOnSingleWheelListener(new OnSingleWheelListener() {
            @Override
            public void onWheeled(int index, String item) {
                //showToast("index=" + index + ", item=" + item);
            }
        });
        picker.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                // showToast("index=" + index + ", item=" + item);
                String[] split = item.split(" ");
                String mm = split[0];
                activityCalculateTvDay.setText(mm);
                menstrualCycle = mm ;
            }
        });
        picker.show();
    }
}
